<?php


namespace XinYaTable\Forms\Services;


use XinYaTable\Forms\Repositories\FormFilterGroupRepository;
use XinYaTable\Forms\Repositories\FormRepository;

class FormFilterGroupService extends BaseService {
    /**
     * @var FormFilterGroupRepository
     */
    private $_formFilterGroupRepository;
    
    /**
     * FormFilterGroupService constructor.
     *
     * @param FormFilterGroupRepository $formFilterGroupRepository
     */
    public function __construct(FormFilterGroupRepository $formFilterGroupRepository) {
        parent::__construct();
        $this->_formFilterGroupRepository = $formFilterGroupRepository;
    }
    
    /**
     * @param int $formId
     * @param int $uid
     *
     * @return \Illuminate\Support\Collection|mixed
     * @throws \XinYaTable\Forms\Exceptions\FormException
     */
    public function getUserFilterGroup(int $uid, int $formId) {
        $_userFilterGroup = $this->_formFilterGroupRepository
            ->getUserFilterGroup($formId, $uid);
        if ($_userFilterGroup->isEmpty()) {
            $_userFilterGroup = $this->_formFilterGroupRepository
                ->syncSystemToUser($formId, $uid);
        }
        
        return $_userFilterGroup;
    }
    
    /**
     * @param array  $groupInfo
     * @param string $tableName
     * @param int    $uid
     *
     * @return \XinYaTable\Forms\Models\EloquentFormFilterGroup
     * @throws \XinYaTable\Forms\Exceptions\FormException
     */
    public function createUserFilterGroup(array $groupInfo, $tableName, int $uid) {
        /** @var FormRepository $formRep */
        $formRep = app(FormRepository::class);
        $formId  = $formRep->getFormByTableName($tableName,true);
        
        $this->_formFilterGroupRepository->checkFilterGroupRepeat($groupInfo['title'], $uid);
        
        return $this->_formFilterGroupRepository
            ->createUserFilterGroup($groupInfo, $formId, $uid);
    }
    
    /**
     * @param int $id
     * @param int $uid
     *
     * @return \Illuminate\Support\Collection|mixed
     * @throws \XinYaTable\Forms\Exceptions\FormException
     */
    public function deleteUserFilterGroup(int $id, int $uid) {
        $deleteFilter = $this->_formFilterGroupRepository->deleteFilterGroup($id, $uid);
    
        return $this->getUserFilterGroup($uid, $deleteFilter->form_id);
    }
    
    /**
     * @param array $filterGroup
     * @param int   $id
     * @param int   $uid
     *
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|null|object
     * @throws \XinYaTable\Forms\Exceptions\FormException
     */
    public function updateUserFilterGroup(array $filterGroup, int $id, int $uid) {
        isset($filterGroup['title']) && $this->_formFilterGroupRepository
            ->checkFilterGroupRepeat($filterGroup['title'], $uid, $id);
        
        return $this->_formFilterGroupRepository->updateFilterGroup($filterGroup, $id, $uid);
    }
    
}